package de.schule.barnimgymnasium.javafx.broadcaster;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import javafx.scene.image.Image;

public class MemberProfile implements Serializable {

    private static final long serialVersionUID = -6858035930765423222L;
    private String nickname;
    private transient final int MAX_IMAGE_LENGTH = 65400;
    private byte[] face;
    private Gender gender;
    private transient Image faceImage;

    MemberProfile(final String nickname, final File faceFile, final Gender gender) {
        this.nickname = nickname;
        this.setFace(faceFile);
        this.gender = gender;
    }

    enum Gender {
        MALE("männlich"), FEMALE("weiblich"), OTHER("intersexuell");

        final String text;

        private Gender(final String txt) {
            this.text = txt;
        }
    }

    public String getNickname() {
        return this.nickname;
    }

    void setNickname(final String nickname) {
        if (nickname == null || nickname.isEmpty()) {
            return;
        }
        this.nickname = nickname;
    }

    // public byte[] getImage() {
    // return this.face;
    // }
    //
    // void setImage(final byte[] face) {
    // this.face = face;
    // }

    public Gender getGender() {
        return this.gender;
    }

    void setGender(final Gender g) {
        if (g == null) {
            return;
        }
        this.gender = g;
    }

    public Image getFaceAsImage() {
        if (this.faceImage == null && this.face != null) {
            this.faceImage = new Image(new ByteArrayInputStream(this.face));
        }
        return this.faceImage;
    }

    public void setFace(final File choosen) {
        if (choosen == null) {
            this.face = null;
            this.faceImage = null;
            return;
        }
        try (FileInputStream fis = new FileInputStream(choosen)) {
            final byte[] b = new byte[this.MAX_IMAGE_LENGTH];
            int off = 0;
            int len = this.MAX_IMAGE_LENGTH;
            int read;
            while ((read = fis.read(b, off, len)) != -1) {
                if (len == 0 && read == 0) {
                    // Datei ist zu groß, nichts ändern
                    return;
                }
                off += read;
                len -= read;
            }
            this.face = new byte[off];
            System.arraycopy(b, 0, this.face, 0, off);
        } catch (final IOException e) {
            // nichts ändern
            return;
        }
    }
}
